﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using zhangmenren.IService;
using zhangmenren.Models;
using zhangmenren.Models.help;
using zhangmenren.Untils;
using Microsoft.AspNetCore.Http;
using System.Linq;

namespace zhangmenren.Controllers
{
	/// <summary>
	/// 
	/// </summary>
	public class OrderController : Controller
	{
		private IWorksService worksService;
		private IOrderService orderService;
		private ICensusService censusService;
		public OrderController(IWorksService _worksService, IOrderService _orderService, ICensusService _censusService)
		{
			worksService = _worksService;
			orderService = _orderService;
			censusService = _censusService;
		}
		public async Task<IActionResult> Index(int id)
		{
            var user = QTCookie.GetCookie<UserCook>(HttpContext);
            if (user == null)
            {
                return Json(new { state = "login", msg = "请重新登录", });
            }
            var result = await worksService.FindById(id);
			return View(result);
		}

		public async Task<JsonResult> SubOrder(OrderEntity entity)
		{
			var user = QTCookie.GetCookie<UserCook>(HttpContext);
			if (user == null)
			{
				return Json(new { state = "login", msg = "请重新登录", });
			}
			var work = await worksService.FindById(entity.WorkId);
			entity.OrderId = DateTime.Now.ToString("yyyyMMddHHmmssff") + RandomHelper.GenerateRandomCode(5);
			entity.UserId = user.Id;
			entity.WorkTitle = work.Title;
			entity.Price = work.Price;
			entity.Num = 1;
			var result = await orderService.Add(entity);
			return Json(new { state = "ok", msg = "成功", channel = entity.PayType, orderid = entity.OrderId, title = entity.WorkTitle, amount = entity.Price });
		}

        [HttpPost]
		public async Task<JsonResult> PaySuccessAjax(string orderId)
		{
			var result = await orderService.Payed(orderId);
			var order = await orderService.FindById(orderId);
			CensusEntity cen = new CensusEntity();
			cen.Type = 3;
			cen.UserId = order.UserId;
			cen.WorkId = order.WorkId;
			var addcen = await censusService.Add(cen);
			return Json(new { state = "ok", msg = "成功", });
		}


		public IActionResult PaySuccess()
		{
			return View();
		}


        [HttpPost]
        public async Task< IActionResult> PaySuccessAli()
        {
            //这是签名验证串，请在本平台 App设置 查询或重置
            const string APP_SECRET = "JYVjTcXTyTWXRXRnAAeZuRks20En9g29";
            const int CH_WeiXin = 0;    //支付渠道：微信
            const int CH_Alipay = 1;    //支付渠道：支付宝
            HttpContext.Response.Clear();
            if (!"POST".Equals(HttpContext.Request.Method, StringComparison.OrdinalIgnoreCase))
            {
                //不是 POST 方法
                await HttpContext.Response.WriteAsync("FAIL");
            }
            string sign = "";
            var dict = new SortedDictionary<string, string>();
            foreach (var k in HttpContext.Request.Form.Keys)
            {
                if (k == "sign")
                {
                    sign = Request.Form[k];
                    continue;
                }
                dict.Add(k, Request.Form[k]);
            }
            if (string.IsNullOrEmpty(sign) || (dict.Count == 0))
            {
                //没有签名信息
               await HttpContext.Response.WriteAsync("FAIL");
            }
            //验证签名
            var s = string.Join("&", dict.Select(x => x.Key + "=" + x.Value)) + APP_SECRET;
            var md5 = MD5.Create();
            var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(s));
            var sn = BitConverter.ToString(bs, 0).Replace("-", "");
            if (!sign.Equals(sn, StringComparison.OrdinalIgnoreCase))
            {
                //签名错误
                await HttpContext.Response.WriteAsync("FAIL");
            }

            //获取有效的参数值
            var tradeid = dict["tradeid"];  //支付平台上的交易号
            var orderid = dict["orderid"];  //订单号
            var amount = Convert.ToDecimal(dict["amount"]);  //支付金额
            var channel = Convert.ToInt32(dict["channel"]);  //支付渠道

            //用上面的参数处理支付成功的后续业务
            //请在这里自由发挥，尽量不要修改其他地方
            //do something...


            var result = await orderService.Payed(orderid);
            var order = await orderService.FindById(orderid);
            CensusEntity cen = new CensusEntity();
            cen.Type = 3;
            cen.UserId = order.UserId;
            cen.WorkId = order.WorkId;
            var addcen = await censusService.Add(cen);

            //处理成功后，http 要返回 OK 字符，否则你的服务器可能会多次收到确认通知
            await HttpContext.Response.WriteAsync("OK");

            return View();
        }
    }



    }
